-module(main).
-define(SERVER_APPS, [sasl,gz]).

-export([start_server/0,stop_server/0,info/0]).

start_server()->
	try
		ok = start_applications(?SERVER_APPS)
	after
		timer:sleep(100)
	end.

stop_server()->
	stop_applications(?SERVER_APPS).	

info() ->
    SchedId      = erlang:system_info(scheduler_id),
    SchedNum     = erlang:system_info(schedulers),
    ProcCount    = erlang:system_info(process_count),
    ProcLimit    = erlang:system_info(process_limit),
    ProcMemUsed  = erlang:memory(processes_used),
    ProcMemAlloc = erlang:memory(processes),
    MemTot       = erlang:memory(total),
    io:format( "abormal termination:
                       ~n   Scheduler id:                         ~p
                       ~n   Num scheduler:                        ~p
                       ~n   Process count:                        ~p
                       ~n   Process limit:                        ~p
                       ~n   Memory used by erlang processes:      ~p
                       ~n   Memory allocated by erlang processes: ~p
                       ~n   The total amount of memory allocated: ~p
                       ~n",
                            [SchedId, SchedNum, ProcCount, ProcLimit,
                             ProcMemUsed, ProcMemAlloc, MemTot]),
      ok.	

manage_applications(Do,Undo,SkipError,ErrorTag,Apps)->
	lists:foldl(
			fun(App,Acc)->
				case Do(App) of
					ok -> [App|Acc];
					{error, {SkipError, _}} -> Acc;
					{error, Reason} ->
						lists:foreach(Undo, Acc),
						throw({error, {ErrorTag, App, Reason}})
				end
			end,[],Apps),
	ok.
	
start_applications(Apps)->
	manage_applications(fun application:start/1,
						fun application:stop/1,
						already_started,
						cannot_start_application,
						Apps).

						
stop_applications(Apps)->
	manage_applications(fun application:stop/1,
						fun application:start/1,
						not_started,
						cannot_stop_application,
						Apps).		